package luj.tool.jnproxyan.proxy.network.ssh.connect;

import luj.bean.api.BeanContext;
import luj.bean.api.bean.Bean;
import luj.cluster.api.actor.Tellable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PipedInputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RemoteDataReceiver {

  public RemoteDataReceiver(PipedInputStream in, byte[] readBuf, Tellable socksRef, Long reqId, BeanContext lujbean) {
    _in = in;
    _readBuf = readBuf;
    _socksRef = socksRef;
    _reqId = reqId;
    _lujbean = lujbean;
  }

  public void receive() {
    EXEC.submit(this::recvImpl);
  }

  private void recvImpl() {
    try {
      int len = _in.read(_readBuf);
      if (len < 1) {
        LOG.debug("网站断开");
        return;
      }

      LOG.debug("网站通过SSH发来，大小：{}", len);
      byte[] data = new byte[len];
      System.arraycopy(_readBuf, 0, data, 0, len);

//      Bean<Server2CForwardMsg> msg = _lujbean.createBean(Server2CForwardMsg.class);
//      msg.setField(m -> m::reqId, _reqId);
//      msg.setField(m -> m::data, data);
//      _socksRef.tell(msg.getValueInstance());
//
//      new RemoteDataReceiver(_in, _readBuf, _socksRef, _reqId, _lujbean).receive();

    } catch (IOException e) {
      LOG.error(e.getMessage(), e);
    }
  }

  private static final Logger LOG = LoggerFactory.getLogger(RemoteDataReceiver.class);
  private static final ExecutorService EXEC = Executors.newCachedThreadPool();

  private final PipedInputStream _in;
  private final byte[] _readBuf;

  private final Tellable _socksRef;
  private final Long _reqId;

  private final BeanContext _lujbean;
}
